﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Linq;
using Microsoft.Extensions.DiagnosticAdapter;

namespace Cngot.Extensions.Trace.Http
{
    internal sealed class DiagnosticObserver
    {
        private static string[] RequestBodyMethods = new string[] { "post", "put" };
        //private ConcurrentDictionary<string, long> startTimes = new ConcurrentDictionary<string, long>();
        private readonly ILogger _logger;
        private readonly ILogEventPropertyFactory _dia;
        public DiagnosticObserver(ILoggerFactory loggerFactory, ILogEventPropertyFactory dia)
        {
            _logger = loggerFactory.CreateLogger("Cngot.Extensions.Trace.Http");
            _dia = dia;
        }

        [DiagnosticName("Microsoft.AspNetCore.Hosting.BeginRequest")]
        public void BeginRequest(HttpContext httpContext, long timestamp)
        {
            //startTimes.TryAdd(httpContext.TraceIdentifier, timestamp);
        }

        [DiagnosticName("Microsoft.AspNetCore.Hosting.EndRequest")]
        public void EndRequest(HttpContext httpContext, long timestamp)
        {
            //startTimes.TryGetValue(httpContext.TraceIdentifier, out long startTime);

            //var elapsedMs = ((double)timestamp - startTime) / TimeSpan.TicksPerMillisecond;


            //_logger.LogTrace(JsonSerializer.Serialize(new
            //{
            //    Method = httpContext.Request.Method,
            //    StatusCode = httpContext.Response.StatusCode,
            //    Url = httpContext.Request.Path + httpContext.Request.QueryString,
            //    ClientIp = httpContext.Connection.RemoteIpAddress.MapToIPv4().ToString(),
            //    //Header = _httpTraceOption.RequestDelegate(httpContext.Request),
            //    Request = Activity.Current?.GetCustomProperty("http.request"),
            //    Response = Activity.Current?.GetCustomProperty("http.response")
            //}));

            var arr = _dia.TagObjects.Where(w => w.Key.StartsWith("http.")).OrderBy(w => w.Key).ToDictionary(w => w.Key.Replace("http.", "{") + "}", w => w.Value);
            if (arr.Any())
            {
                string format = string.Join(",", arr.Keys);
                //_logger.LogTrace("${method},${aaa}", httpContext.Request.Method, "ddddd");
                _logger.LogTrace(format, arr.Values.ToArray());
            }
            //startTimes.TryRemove(httpContext.TraceIdentifier, out _);
        }
    }
}
